<template>
  <div id="labreportitemRefer">
    <Splitpanes horizontal class="horizontalLine">
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">危急值</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="loading" @click="findItemDictRefer"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAdd"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="handleSave" :loading="saveLoading"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBody">
          <vxe-table ref="itemDictCriticalTable" v-loading="loading" class="mytable-scrollbar" :row-config="{ isCurrent: true, isHover: true }" :data="tableList" border style="width: 100%" height="auto" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="rowClick" resizable show-overflow :column-config="{ resizable: true }">
            <vxe-column field="seq" title="序号" width="30" type="seq" :align="'left'"></vxe-column>
            <vxe-column title="低危显示标志" field="lowText" :align="'left'" width="100" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                {{ row.lowText }}
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.lowText" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="lowerLimit" title="下限" width="50" :align="'left'" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.lowerLimit }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.lowerLimit" placeholder="请输入下限" style="width: 100%" @blur="handleBlurLowerLimit(row, rowIndex)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="upperLimit" title="上限" width="50" :align="'left'" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.upperLimit }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.upperLimit" placeholder="请输入上限" style="width: 100%" @blur="handleBlurUpperLimit(row, rowIndex)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="高危显示标志" field="upText" :align="'left'" width="100" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                {{ row.upText }}
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.upText" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="颜色显示为" field="colorFor" :align="'left'" width="85" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <span v-if="row.colorFor === '0' || row.colorFor === null">采用全局</span>
                <span v-if="row.colorFor === '1'">背景颜色</span>
                <span v-if="row.colorFor === '2'">背景颜色</span>
              </template>
              <template #edit="{ row }">
                <!-- <vxe-input v-model="row.colorFor" type="text"></vxe-input> -->
                <vxe-select v-model="row.colorFor" placeholder="颜色显示为" clearable>
                  <vxe-option :value="'0'" :label="`采用全局`"></vxe-option>
                  <vxe-option :value="'1'" :label="`背景颜色`"></vxe-option>
                  <vxe-option :value="'2'" :label="`文字颜色`"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>

            <vxe-column title="低危颜色值" field="lowCatchColor" :align="'left'" width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <el-color-picker v-model="row.lowCatchColor" />
                <span v-if="row.lowCatchColor" class="margin-left-xs padding-lr-xs" :style="{ background: `${row.lowCatchColor}` }">{{ row.lowCatchColor }}</span>
              </template>
              <template #edit="{ row }">
                <el-color-picker v-model="row.lowCatchColor" />
                <span v-if="row.lowCatchColor" class="margin-left-xs padding-lr-xs" :style="{ background: `${row.lowCatchColor}` }">{{ row.lowCatchColor }}</span>
              </template>
            </vxe-column>

            <vxe-column title="高危颜色值" field="catchColor" :align="'left'" width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <!-- <span style="width:22px;height:22px" :style="{ background: `${row.catchColor}` }"></span>
                <span>{{ row.catchColor }}</span> -->
                <el-color-picker v-model="row.catchColor" />
                <span v-if="row.catchColor" class="margin-left-xs padding-lr-xs" :style="{ background: `${row.catchColor}` }">{{ row.catchColor }}</span>
              </template>
              <template #edit="{ row }">
                <!-- <vxe-input v-model="row.catchColor" type="text"></vxe-input> -->
                <el-color-picker v-model="row.catchColor" />
                <span v-if="row.catchColor" class="margin-left-xs padding-lr-xs" :style="{ background: `${row.catchColor}` }">{{ row.catchColor }}</span>
              </template>
            </vxe-column>
            <vxe-column field="factorDescribe" title="条件描述" width="160" :align="'left'" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.factorDescribe }}</div>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.factorDescribe" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="factor" title="条件" :align="'left'" width="160" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.factor }}</div>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.factor" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="isEnable" width="90" title="是否启用" :align="'center'">
              <template #default="{ row }">
                <vxe-switch v-model="row.isEnable" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="referList" title="规则中设置数据" :align="'left'" :visible="false"></vxe-column>
            <vxe-column field="selectValue" title="选中的规则" :align="'left'" :visible="false"></vxe-column>
            <vxe-column title="危急值显文本" field="displayText" :align="'left'" width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                {{ row.displayText }}
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.displayText" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="range" title="危急值范围" width="100" :align="'left'" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.range }}</div>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.range" placeholder="危急值范围" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>

      </Pane>
      <Pane size="50">
        <div class="toolbartitle">规则设置</div>
        <div class="tableBody">
          <formulaTools ref="referFormRef" @repressChange="getRefer" />
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, onMounted, getCurrentInstance, watch, defineProps } from 'vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { AppStore } from '@/stores/store';
import { Splitpanes, Pane } from 'splitpanes';
import formulaTools from '@/components/FormulaTools.vue';
import { IsEmpty } from '@/utils/common';
import { isEmpty } from 'xe-utils';

defineExpose({ initPage });

let disabledTag = ref(true); //中间质控品维护按钮标记

let staItemDict = ref(null);

function initPage(row: any) {
  if (isEmpty(row)) {
    staItemDict.value = {};
  } else {
    staItemDict.value = row;
    findItemDictRefer();
  }
  if (!staItemDict.value.id) {
    disabledTag.value = true;
  } else {
    disabledTag.value = false;
  }
}

let store = AppStore();
let showLoading = ref(false);
let { proxy }: any = getCurrentInstance();
let saveLoading = ref(false); //保存

// 方法定义区 =============
onMounted(() => {});
let tableList = reactive([]);
let loading = ref(false);
let referFormRef: any = ref(null); //规则回显数据
let referForm = {
  selectValue: '',
  referList: ''
};
//上限光标移出事件
function handleBlurUpperLimit(row, rowIndex) {
  if (!IsEmpty(row.lowerLimit)) {
    tableList[rowIndex].range = row.lowerLimit + '-' + row.upperLimit;
  }
}
//下限光标移出事件
function handleBlurLowerLimit(row, rowIndex) {
  if (!IsEmpty(row.upperLimit)) {
    tableList[rowIndex].range = row.lowerLimit + '-' + row.upperLimit;
  }
}

function findItemDictRefer() {
  tableList.length = 0;

  loading.value = true;
  const url = '/lis/sta/staItemDictCritical/findStaItemDictCritical';
  proxy.$http
    .get(url, { params: { itemNo: staItemDict.value.itemNo } })
    .then((res: any) => {
      tableList.length = 0;
      if (res.status.code === 200) {
        tableList.push(...res.data);
        if (tableList.length > 0) {
          rowClick({
            row: tableList[0],
            rowIndex: 0
          });
        } else {
          referForm.referList = '';
          referForm.selectValue = '';
          referFormRef.value.initReferForm(referForm);
        }
      }

      loading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      loading.value = false;
    });
}

let rowdata = {}; //点击当前行的数据
let rowIndexClick = 0; //点击当前行下标
// 表格点击当前行
function rowClick({ row, rowIndex }: any) {
  rowIndexClick = rowIndex;
  rowdata = row;
  loading.value = false;
  const $itemDictCriticalTable = proxy.$refs.itemDictCriticalTable;
  if ($itemDictCriticalTable) {
    $itemDictCriticalTable.setCurrentRow(row);
  }
  referForm.referList = row.referList;
  referForm.selectValue = row.selectValue;
  referFormRef.value.initReferForm(referForm);
}

//删除参考范围信息
function handleDelete() {
  if (rowdata.id === '') {
    //没有做存储时，直接删除当前新增的列
    tableList.splice(rowdata.seq - 1, 1);
    return;
  }
  proxy
    .$confirm('确定要删除当前勾选的数据？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      proxy.$http
        .post('/lis/sta/staItemDictCritical/deleteStaItemCritical', { id: rowdata.id })
        .then((res: any) => {
          if (res.status.code === 1) {
            findItemDictRefer();
            VxeMessage('删除成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('删除异常', VxeNotifyType.error);
        });
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 新增参考范围
function handleAdd() {
  tableList.push({
    id: '',
    seq: tableList.length + 1,
    displayText: '',
    upperLimit: '',
    lowerLimit: '',
    factor: '',
    range: '',
    itemNo: staItemDict.value.itemNo,
    selectValue: '',
    referList: '',
    factorDescribe: '',
    isEnable: '1',
    lowText: '',
    upText: '',
    catchColor: '#FF0000',
    lowCatchColor: '#FF0000',
    colorFor: '0'
  });
}
let sqlExpress = '';
let referListJson = '';
let selectValue = '';
let factorDescribe = '';

//规则组件返回值
function getRefer(referTab: any) {
  // 实时插入点击的规则当前行中
  if (tableList.length > 0) {
    tableList[rowIndexClick].referList = IsEmpty(JSON.stringify(referTab.tab)) ? '' : JSON.stringify(referTab.tab);
    tableList[rowIndexClick].factor = IsEmpty(referTab.sqlExpress) ? '' : referTab.sqlExpress;
    tableList[rowIndexClick].selectValue = IsEmpty(JSON.stringify(referTab.selectValue)) ? '' : JSON.stringify(referTab.selectValue);
    tableList[rowIndexClick].factorDescribe = IsEmpty(referTab.factorDescribe) ? '' : referTab.factorDescribe;
  }
}

let itemDictCriticalTable = ref();
// 点击修改新增保存
async function handleSave() {
  if (tableList.length === 0) {
    VxeMessage('务必先新增参考范围-----点击【新增】设置区间范围》》规则设置', VxeNotifyType.error);
    return;
  } else {
    saveLoading.value = true;
    const url = '/lis/sta/staItemDictCritical/saveOrUpdateStaCritical';
    proxy.$http
      .post(url, tableList)
      .then((res: any) => {
        VxeMessage('保存成功', VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage('保存失败', VxeNotifyType.success);
      });
    setTimeout(() => {
      findItemDictRefer();
      saveLoading.value = false;
    }, 500);
  }
}
</script>
<style lang="scss" scoped>
#labreportitemRefer {
  width: 100%;
  height: 100%;

  .horizontalLine {
    :deep(.splitpanes__splitter) {
      background-color: $base-white;
    }
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  .tableBody {
    height: calc(100% - 40px);
  }
}
</style>
